﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jayden.Dll.Core.Collections.Generic
{
	public class TreeSet<T> where T : IComparable<T>
	{
		protected IBinaryTree<T> m_Root;
		protected int m_Count;

		public virtual void Add(T item)
		{
			if (m_Root == null)
				m_Root = new BinaryTree<T>(item);
			else
			{
				int compare;
				bool added = false;
				IBinaryTree<T> current = m_Root;
				while (!added)
				{
					compare = current.Value.CompareTo(item);
					if (compare < 0 && current.Left == null)
					{
						current.Left = new BinaryTree<T>(item);
						added = true;
					}
					else if (compare < 0)
						current = current.Left;
					else if (current.Right == null)
					{
						current.Right = new BinaryTree<T>(item);
						added = true;
					}
					else
						current = current.Right;
				}
			}
			m_Count++;
		}
		public void Clear()
		{
			m_Root = null;
			m_Count = 0;
		}
		public bool Contains(T item)
		{
			IBinaryTree<T> current = m_Root;
			while (current != null)
			{
				int compare = current.Value.CompareTo(item);
				if (compare == 0)
					return true;
				if (compare < 0)
					current = current.Left;
				else
					current = current.Right;
			}
			return false;
		}

		public IEnumerator<T> GetEnumerator()
		{
			List<T> enumerable = new List<T>();
			if (m_Root != null)
				((BinaryTree<T>)m_Root).ExecuteLeftParentRight(delegate(T item) { enumerable.Add(item); });
			return enumerable.GetEnumerator();
		}
	}
}
